//
//  ViewController.swift
//  Checklists
//
//  Created by M.I. Hollemans on 15/09/14.
//  Copyright (c) 2014 Razeware. All rights reserved.
//

import UIKit

class ChecklistViewController: UITableViewController, ItemDetailViewControllerDelegage {

    var checklist: Checklist!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    tableView.rowHeight = 44
    title = checklist.name
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

    
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return checklist.items.count
  }
  
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("ChecklistItem") as UITableViewCell
    
    let item = checklist.items[indexPath.row]
    
    configureTextForCell(cell, withChecklistItem: item)
    configureCheckmarkForCell(cell, withChecklistItem: item)
    
    return cell
  }
  
  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let cell = tableView.cellForRowAtIndexPath(indexPath) {
      let item = checklist.items[indexPath.row]
      item.toggleChecked()
      
      configureCheckmarkForCell(cell, withChecklistItem: item)
    }
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
//    saveChecklistItems()
  }

    // 删除数据项
  override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    
    // 从表中删除
    checklist.items.removeAtIndex(indexPath.row)
    
    // 从界面中删除
    let indexPaths = [indexPath]
    tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
//    saveChecklistItems()
  }

  func configureCheckmarkForCell(cell: UITableViewCell, withChecklistItem item: ChecklistItem) {
    
    let label = cell.viewWithTag(1001) as UILabel
    
    if item.checked {
      label.text = "✔︎"
    } else {
      label.text = ""
    }
  }
    
    // 根据数据项目，将文字写于label上
  func configureTextForCell(cell: UITableViewCell, withChecklistItem item: ChecklistItem) {
    let label = cell.viewWithTag(1000) as UILabel
    label.text = item.text
  }
    
    // Step 4： 实现代理方法，这里是具体的做事的人了。
    func itemDetailViewControllerDidCancel(controller: ItemDetailViewController) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func itemDetailViewController(controller: ItemDetailViewController, didFinishAddingItem item: ChecklistItem) {
        let newRowIndex = checklist.items.count
        
        checklist.items.append(item)
        let indexPath = NSIndexPath(forItem: newRowIndex, inSection: 0)
        tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        
        dismissViewControllerAnimated(true, completion: nil)
//        saveChecklistItems()
    }
    
    func addItemviewController(controller: ItemDetailViewController, didFinishEditingItem item: ChecklistItem) {
        
        // 先找到该数据在数组中的索引
        if let index = find(checklist.items, item) {
            // 根据索引，获取indexPath
            let indexPath = NSIndexPath(forItem: index, inSection: 0)
            // 由读到cell上的内容
            if let cell = tableView.cellForRowAtIndexPath(indexPath) {
                configureTextForCell(cell, withChecklistItem: item)
            }
        }
        dismissViewControllerAnimated(true, completion: nil)
//        saveChecklistItems()
    }
    
    // Step 5: 最后一步，通知下B，A现在开始，就是你的代理了，你有啥吩咐，就直接只接可以说了
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // 1
        if segue.identifier == "AddItem" {
            // 2
            let navigationController = segue.destinationViewController as UINavigationController
            
            // 3
            let controller = navigationController.topViewController as ItemDetailViewController
            // 4 调用委托方法的代理变量，该变量的值 ，就即此类，从而达到绑定的效果
            controller.delegate = self
        } else if segue.identifier == "EditItem" {
            // 2
            let navigationController = segue.destinationViewController as UINavigationController
            
            // 3
            let controller = navigationController.topViewController as ItemDetailViewController
            // 4 调用委托方法的代理变量，该变量的值 ，就即此类，从而达到绑定的效果
            controller.delegate = self
            
            if let indexPath = tableView.indexPathForCell(sender as UITableViewCell) {
                controller.itemToEdit = checklist.items[indexPath.row]
            }
        }
    }

}
